package com.mrx.example.servlet;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mrx.example.model.BaseModel;
import com.mrx.example.model.PostBody;
import org.apache.commons.io.IOUtils;

/**
 * 最基础的 Servlet, 封装了一些有用的方法, 所有 Servlet 都应该从此类派生
 *
 * @author Mr.X
 */
public abstract class BaseServlet extends HttpServlet {

    /**
     * 发送一个 RESTful 200 响应
     *
     * @param resp  响应对象
     * @param model 响应内容
     * @throws IOException 抛出异常
     */
    protected final void sendModelResponse(HttpServletResponse resp, BaseModel model) throws IOException {
        sendResponse(resp, model, 200);
    }

    /**
     * 发送一个 RESTful 404 响应
     *
     * @param resp  响应对象
     * @param model 响应内容
     * @throws IOException 抛出异常
     */
    protected final void send404ModelResponse(HttpServletResponse resp, BaseModel model) throws IOException {
        sendResponse(resp, model, 404);
    }

    /**
     * 发送一个 RESTful 响应
     *
     * @param resp   响应对象
     * @param model  响应内容
     * @param status 响应代码
     * @throws IOException 抛出异常
     */
    private void sendResponse(HttpServletResponse resp, BaseModel model, Integer status) throws IOException {
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.setStatus(status);
        resp.getWriter().write(model.toJSONString());
    }

    /**
     * 处理跨域问题, 允许跨域
     */
    @Override
    protected final void doOptions(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Headers", "*");
        super.doOptions(req, resp);
    }

    /**
     * 判断所给参数中是否含有 NULL 或 空白字符串
     *
     * @param args 要判断的参数
     * @return 如果含有 null 就返回 true
     */
    protected final boolean hasBlankOrNull(String... args) {
        if (args.length == 0) {
            return true;
        }
        for (String s : args) {
            if (s == null || s.length() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断所给参数中是否全为 NULL
     *
     * @param args 要判断的参数
     * @return 如果全为 null 就返回 true
     */
    protected final boolean allNull(Object... args) {
        if (args.length == 0) {
            return true;
        }
        for (Object o : args) {
            if (o != null) {
                return false;
            }
        }
        return true;
    }

    /**
     * 从 request 中获取 postBody
     *
     * @param request 要获取的 request
     * @return 获取到的 postBody
     * @throws IOException 出现异常时直接抛出
     */
    protected PostBody getPostBody(HttpServletRequest request) throws IOException {
        return new PostBody(request);
    }
}
